import {Component, OnInit} from '@angular/core';
import {CommodityService} from './commodity.service';
import {Route, Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd/message';

interface Query {
  goodsName: string;
  goodsTypeList: [];
  status: string;
  date: any;
  // 当前页
  page: number;
  // 分页大小
  pageSize: number;
}

@Component({
  selector: 'app-commodity',
  templateUrl: './commodity.component.html',
  styleUrls: ['./commodity.component.scss']
})
export class CommodityComponent implements OnInit {
  query: Query = {
    goodsName: '',
    goodsTypeList: [],
    status: '',
    date: [],
    // 当前页
    page: 1,
    // 分页大小
    pageSize: 20,
  };
  listOfData = {
    total: 0,
    records: []
  };
  checked = false;
  setOfCheckedId = new Set();
  indeterminate = false;
  categoryOptions = [];

  // 缓存恢复
  static updateCache: any = null;

  constructor(
    private commodityService: CommodityService,
    private router: Router,
    private nzMessageService: NzMessageService
  ) {
  }

  ngOnInit(): void {
    this.queryCategory();

    CommodityComponent.updateCache = () => {
      this.queryTableList();
    }

    this.queryTableList();
  }

  /*
  * 查询商品分类
  * */
  queryCategory() {
    this.commodityService.httpGet(this.commodityService.serviceUrl.category, {isAvailable: 1}).then((res: any) => {
      this.categoryOptions = res.data;
      // this.categoryOptions = this.formatCateGory(res.data);
    }).catch(err => {
      console.log(err);
    });
  }

  queryBtn() {
    this.query.page = 1;
    this.queryTableList();
  }

  resetCondition() {
    this.query = {
      goodsName: '',
      goodsTypeList: [],
      status: '',
      date: [],
      page: 1,
      pageSize: 20,
    };
    this.queryTableList();
  }

  queryTableList(): void {
    this.setOfCheckedId = new Set();
    this.indeterminate = false;
    this.checked = false;
    this.listOfData = {
      total: 0,
      records: []
    };
    this.commodityService.httpGet(this.commodityService.serviceUrl.commodityList, {
      goodsName: this.query.goodsName,
      startTime: this.query.date.length ? +this.query.date[0] : '',
      endTime: this.query.date.length ? +this.query.date[1] : '',
      page: this.query.page,
      pageSize: this.query.pageSize,
      status: this.query.status || '',
      goodsTypeList: this.query.goodsTypeList.join(',')
    }).then((res: any) => {
      if (res.code === 0) {
        this.listOfData = res.data;
      }
    });
  }

  onPageIndexChange(index: number) {
    this.query.page = index;
    // this.checked = false;
    this.queryTableList();
  }

  onPageSizeChange(size: number) {
    this.query.page = 1;
    this.query.pageSize = size;
    // this.checked = false;
    this.queryTableList();
  }

  onAllChecked(check: boolean) {
    if (check) {
      this.listOfData.records.forEach((item: any) => {
        this.setOfCheckedId.add(item.id);
      });
    } else {
      this.setOfCheckedId.clear();
    }
    this.refreshCheckedStatus();
  }

  onItemChecked(id: any, check: boolean) {
    if (check) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfData.records.every(({id}) => this.setOfCheckedId.has(id));
    this.indeterminate = this.listOfData.records.some(({id}) => this.setOfCheckedId.has(id)) && !this.checked;
  }

  // 新增或修改
  gotoPage(value: string, detail?: any) {
    this.router.navigate([`customization/commodity-${value}`], {queryParams: {detail: JSON.stringify(detail)}});
  }

  // 删除商品
  deleteCommodity(id: any) {
    this.commodityService.httpGet(this.commodityService.serviceUrl.commodityDelete, {id}).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.queryTableList();
      }
    });
  }

  // 批量上架下架
  batchOperation(upOrDown: number) {
    this.putawayCommoditys(Array.from(this.setOfCheckedId), upOrDown);
  }

  // 上架下架
  putawayCommodity(item: any) {
    if (item.status === 1) {
      this.putawayCommoditys([item.id], 0);
    } else if (item.status === 2) {
      this.putawayCommoditys([item.id], 1);
    }
  }

  // 0 下架 1 上架
  putawayCommoditys(list: any[], upOrDown: number) {
    if (!list.length) {
      this.nzMessageService.warning('没有选中数据');
      return;
    }
    this.commodityService.httpPost(this.commodityService.serviceUrl.commodityPutaway, {
      goodsIdList: list.join(','),
      upOrDown
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.queryTableList();
      }
    });
  }
}
